package com.xbongbong.paas.help.subform;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.saas.domain.entity.ProductUserEntity;
import com.xbongbong.saas.domain.entity.UserAndDepTeamEntity;
import com.xbongbong.saas.enums.subform.ProductTeamEnum;
import com.xbongbong.paas.help.subform.abstracts.AbstractUserAndDepTeamTransferSubForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 产品 es和数据库格式转化
 * @author 魏荣杰
 * @date 2020/8/24 10:27
 * @since
 * @version
 */
@Component
public class ProductTeamTransferSubForm extends AbstractUserAndDepTeamTransferSubForm {

    private static final Logger LOG = LoggerFactory.getLogger(ProductTeamTransferSubForm.class);


    @Override
    public PaasFormDataEntity transferTeamToFormData(UserAndDepTeamEntity userAndDepTeamEntity) {
        ProductUserEntity productUserEntity = (ProductUserEntity) userAndDepTeamEntity;
        PaasFormDataEntity paasFormDataEntity = createPaasFormDataEntityForUserTeam(productUserEntity);

        JSONObject teamJson = JSONObject.parseObject(JSON.toJSONString(productUserEntity));

        JSONObject data = new JSONObject();

        ProductTeamEnum[] productTeamEnums = ProductTeamEnum.values();
        for (ProductTeamEnum productTeamEnum : productTeamEnums) {
            String dbAttr = productTeamEnum.getDbAttr();
            String dataAttr = productTeamEnum.getDataAttr();
            Integer fieldType = productTeamEnum.getFieldType();
            formatDataForEs(teamJson, data, dbAttr, dataAttr, fieldType);
        }
        paasFormDataEntity.setData(data);

        return paasFormDataEntity;
    }

    @Override
    public UserAndDepTeamEntity transferFormDataToTeam(PaasFormDataEntity paasFormDataEntity) {
        JSONObject data = paasFormDataEntity.getData();

        JSONObject dbData = new JSONObject();
        ProductTeamEnum[] productTeamEnums = ProductTeamEnum.values();
        for (ProductTeamEnum productTeamEnum : productTeamEnums) {
            String dbAttr = productTeamEnum.getDbAttr();
            String dataAttr = productTeamEnum.getDataAttr();
            Integer fieldType = productTeamEnum.getFieldType();
            formatDataForDb(data, dbData, dbAttr, dataAttr, fieldType);

        }
        ProductUserEntity productUserEntity = JSON.parseObject(dbData.toJSONString(), ProductUserEntity.class);
        productUserEntity.setAddTime(paasFormDataEntity.getAddTime());
        productUserEntity.setUpdateTime(paasFormDataEntity.getUpdateTime());
        productUserEntity.setCorpid(paasFormDataEntity.getCorpid());
        productUserEntity.setDel(paasFormDataEntity.getDel());
        productUserEntity.setId(paasFormDataEntity.getId());

        return productUserEntity;
    }
}
